<?php

namespace App\Console\Commands;
use App\Models\ArticleRelateCircle;
use App\Models\Circle;
use App\Models\Subscribe;
use App\Models\UserJoinCircle;
use App\Services\PublishTemplateService;
use Illuminate\Console\Command;

class CircleArticleNoticeCommand extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'circle-article-notice';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = '圈子动态提醒';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return int
     */
    public function handle()
    {
        \Log::info('---------start-circle-article-notice-----------');
        Subscribe::where('type', Subscribe::TYPE_CIRCLE_ARTICLE_NOTICE)->withCertain('user', ['openid'])->chunk(50, function ($list) {
            foreach ($list as $item) {
                $arr_circle_id = UserJoinCircle::where('user_id', $item->user_id)->pluck('circle_id')->all();
                $circle_num = count($arr_circle_id);
                if ($circle_num) {
                    $article_list = ArticleRelateCircle::selectRaw('circle_id,count(*) as total')->whereIn('circle_id', $arr_circle_id)->join('articles', function ($join) {
                        $join->on('articles.id', 'article_relate_circles.article_id')->where('articles.created_at', '>=', date('Y-m-d 00:00:01'));
                    })->groupBy('circle_id')->orderBy('total', 'desc')->get();
                    $res = $article_list->toArray();
                    $article_num = array_sum(array_column($res, 'total'));
                    if ($article_num) {
                        $circle = Circle::where('id', $article_list[0]['circle_id'])->first();
                        $circle_title = $circle->title;
                        $service = new PublishTemplateService();
                        $service->circleArticleNotice($item->user->openid, $circle_title, $circle_num, $article_num, $circle->id, $circle->is_activity);
                    }
                }
            }
        });
        Subscribe::where('type', Subscribe::TYPE_CIRCLE_ARTICLE_NOTICE)->delete();
        \Log::info('---------end-circle-article-notice-----------');
    }
}
